# -*- coding: utf-8 -*-
import os
import configparser
import sys

cnf_file = "myback.ini"
config = configparser.ConfigParser()
config.read(cnf_file)

inner_backup_dir = config.get("myback", "inner_backup_dir")
backupfilelist = os.path.join(inner_backup_dir, "backupfilelist.log")
stop_at = sys.argv[1]
inner_work_dir = config.get("myback", "inner_work_dir")


def get_restorefile_list():
    list_backup = []
    list_restore_file = []
    if os.path.exists(backupfilelist):
        with open(backupfilelist, 'r') as f:
            lines = f.readlines()
            for line in lines:
                list_backup.append(line.replace("\n", ""))
    if (list_backup):
        for i in range(len(list_backup) - 1, -1, -1):
            list_restore_file.append(list_backup[i])
            backup_name = list_backup[i].split("|")[2]
            if "full" in backup_name:
                full_backup_time = list_backup[i].split("|")[1]
                if (stop_at < full_backup_time):
                    break
                else:
                    list_restore_file = None
    # restore file in the list_restore_log
    list_restore_file.reverse()
    return list_restore_file


def apply_log_for_backup():
    list_restore_backup = get_restorefile_list()
    start_flag = 1
    full_backup_path = None

    for current_backup_file in list_restore_backup:
        # 解压备份文件
        current_backup_name = current_backup_file.split("|")[2]
        current_backup_fullname = os.path.join(inner_work_dir, current_backup_name)
        if (start_flag == 1):
            full_backup_path = current_backup_fullname
            start_flag = 0
            print("innobackupex --apply-log --redo-only {0}".format(full_backup_path))
            os.system("innobackupex --apply-log --redo-only {0}".format(full_backup_path))
        else:
            print("innobackupex --apply-log --redo-only {0} --incremental-dir={1}".format(full_backup_path,
                                                                                          current_backup_fullname))
            os.system("innobackupex --apply-log --redo-only {0} --incremental-dir={1}".format(full_backup_path,
                                                                                              current_backup_fullname))
    # apply_log for full backup at last(remove --read-only parameter)
    print("innobackupex --apply-log {0}".format(full_backup_path))
    os.system("innobackupex --apply-log {0}".format(full_backup_path))


if __name__ == '__main__':
    apply_log_for_backup()
